<template>
  <div class="page-home-index">
    <search-bar ref="searchBar" />
    <div class="map" id="coordinates" ref="basicMapbox" :style="{height:domHeight + 'px',width:'100%'}"></div>
  </div>
</template>
<script>
import searchBar from './components/searchBar';
import * as mapboxgl from 'mapbox-gl';
import {city, cityMapCenter, geoserver} from '@/config/env';
export default {
  components:{
    searchBar
  },
  data() {
    return {
      map: null,
      marker: null,
      mapboxToken: 'pk.eyJ1Ijoic25zcXNzIiwiYSI6ImNrZ2oxbWtqMTAzNnAyeXFwMDAzdmp2YTAifQ.AuaHmI9j-_VbOYxUSJACQw',
      meteoblueMaps: null,
      externals: [],
      domHeight: 0,
    }
  },
  async created() {
    this.domHeight = document.body.clientHeight - 60 - 40 - 6;
    await this.loadCss();
    await this.loadScript(
      'https://static.meteoblue.com/cdn/mapbox-gl-js/v1.11.1/mapbox-gl.js',
      'sha512-v5PfWsWi47/AZBVL7WMNqdbM1OMggp9Ce408yX/X9wg87Kjzb1xqpO2Ul0Oue8Vl9kKOcwPM2MWWkTbUjRxZOg=='
    );
    await this.loadScript(
      'https://static.meteoblue.com/lib/maps-plugin/v0.x/maps-plugin.js'
    );
    this.createMap();
  },
  methods: {
    createMap() {
      const map = new mapboxgl.Map({
        container: this.$refs.basicMapbox,
        accessToken: this.mapboxToken,
        center: cityMapCenter,
        zoom: 8.5,
        hash: false,
        attributionControl: false,
        keyboard: false,   
      });
      const lang = 'zh';
      const apiKey = '1iw4Jq5NZK60Ig7O';//'ZEa5n8pTuPwFf0dH'; //
      const maps = 'windAnimation,wind,temperature,obsTemperature,humidity,pressure,totalClouds,highClouds,midClouds,lowClouds,precipitationDaily,obsPrecipitation,solarIradiation,sunshine,temperatureTendency,ozone,particulateMatter,no2,gph500,boundaryLayerHeight,aerosolOpticalDepth,uvIndex,windSpeedAnomaly,temperatureAnomaly,precipAnomaly,gph850temperature,temperatureAnomaly850';
      const overlay = 'windAnimationOverlay,domainBoundary,graticuleOverlay,pressure2mOverlay,temperatureObsOverlay';
      const temperatureUnit = 'C';
      const velocityUnit = 'm/s';


      // The URL to the Inventory JSON. In this case the meteoblue API will generate one with some specified maps.
      const inventoryUrl = `https://maps-api.meteoblue.com/v1/map/inventory/filter?maps=${maps}&overlays=${overlay}&lang=${lang}&apikey=${apiKey}&temperatureUnit=${temperatureUnit}&velocityUnit=${velocityUnit}`;

      // Initialize the meteoblue Maps Plugin. It will generate a user interface on top of the Mapbox GL JS map according to the inventory JSON.
      const meteoblueMaps = new meteoblueMapsPlugin({
        mapboxMap: map,
        inventory: inventoryUrl,
        apiKey: apiKey,
        showSidebar: true,
        timezoneOffsetInSeconds: 28800,
        timezoneAbbreviation: '北京时',
        canUseRestricted: true,
      });
      this.meteoblueMaps = meteoblueMaps;
      map.on('load', () => {
        this.map = map;
        this.addBorder();
      });
      map.on('idle', (evt) => {
        this.addBorder();
      });
    },

    addBorder() {
      if (!this.map) {
        return;
      }
      if (!this.map.getLayer('area-border')) {
        this.map.addLayer({
          id: 'area-border',
          type: 'line',
          'source': {
            'scheme':'tms',
            'type': 'vector',
            'tiles': [
                geoserver + '/gwc/service/tms/1.0.0/air:region@EPSG:900913@pbf/{z}/{x}/{y}.pbf'
            ]
          },
          'source-layer': 'region',
          filter: ['all', ['==', 'name', city], ['==', 'level', 2]],
          minzoom: 1,
          maxzoom: 19,
          paint: {
            'line-color': '#ff9800',
            'line-width': 2
          }
        });
      }
    },

    async loadScript(src, integrity) {
      const head = document.getElementsByTagName('head')[0];
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = src;
      // if (integrity) {
      //   script.integrity = integrity;
      // }
      script.crossorigin = 'anonymous';
      head.append(script);
      this.externals.push(script);
      return new Promise((resolve, reject) => {
        script.onload = () => {
          resolve('success');
        };
        script.onerror = () => {
          reject('error');
        };
      });
    },

    async loadCss() {
      const head = document.getElementsByTagName('head')[0];
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.crossorigin = 'anonymous';
      // link.integrity = 'sha512-xY1TAM00L9X8Su9zNuJ8nBZsGQ8IklX703iq4gWnsw6xCg+McrHXEwbBkNaWFHSqmf6e7BpxD6aJQLKAcsGSdA==';
      link.href = 'https://static.meteoblue.com/cdn/mapbox-gl-js/v1.11.1/mapbox-gl.css';
      head.append(link);
      return new Promise((resolve, reject) => {
        link.onload = () => {
          resolve('success');
        };
        link.onerror = () => {
          reject('error');
        };
      });
    },
    
  }
}
</script>